#pragma once
#include <string>
#include <vector>
#include <fstream>
#include <unordered_map>
#include <cctype>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>


#include "../Log.hpp"
using namespace myLog;


std::unordered_map<int, std::string> Statu2Desc = {
    {100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}
};



std::unordered_map<std::string, std::string> Suffix2Type = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};


/*这个类就是用来实现一些比较零散的功能的*/
class Util{
public:

    /*获取文件的大小*/
    static int FileSize(const std::string& filename){
        std::ifstream ifs(filename, std::ios::binary);
        if(!ifs.is_open()) {
            LOG(LogLevel::ERROR) << filename << " 打开失败";
            return -1;
        }
        ifs.seekg(0, ifs.end);
        int size = ifs.tellg();
        ifs.seekg(0, ifs.beg);
        ifs.close();
        return size;
    }

    /*字符串的分割: 把src中的字符串，按照sep作为分隔符进行分割，最后输出到out*/
    static size_t Split(const std::string& src, const std::string& sep, std::vector<std::string>* out){
        size_t pos = 0, offset = 0;
        while(offset < src.size()){
            pos = src.find(sep, offset);
            if(pos == std::string::npos) {
                /*如果没有找到，那就把offset位置之后的全部取出来放到out数组*/
                out->push_back(src.substr(offset));
                break;
            }
            else{
                /*如果找到，那就取出来放到out数组，前提是取出来的不能是空串*/
                if(offset != pos) out->push_back(src.substr(offset, pos - offset));
                offset = pos + sep.size();   //最后不论如何，都必须把当前这个找到位置给跳过去，要不然会重复进行寻找
            }
        } 
        return out->size();
    }

    /*文件内容的读取，读取完后放入到缓冲区的接收缓冲区内*/
    static bool ReadFromFile(const std::string& filename, std::string* out){
        std::ifstream ifs(filename, std::ios::binary);
        if(!ifs.is_open()) {
            LOG(LogLevel::ERROR) << filename << " OPEN FAILED";
            return false;
        }

        //获取文件的大小
        int fsize = FileSize(filename);
        if(fsize == -1) return false;

        //进行读取
        out->resize(fsize);
        ifs.read(&((*out)[0]), fsize);
        if(!ifs.good()){
            LOG(LogLevel::ERROR) << "READ FROM " << filename << "ERROR"; 
            ifs.close();
            return false; 
        }        
        ifs.close();
        return true;
    }

    /*向文件内写入*/
    static bool WriteIntoFile(const std::string& filename, const std::string& data){
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);  //意思是：使用二进制打开，trunc表示的是：不存在创建，存在就清空重新写入
        if(!ofs.is_open()) {
            LOG(LogLevel::ERROR) << filename << " OPEN FAILED";
            return false;
        }

        ofs.write(data.c_str(), data.size());
        if(!ofs.good()){
            LOG(LogLevel::ERROR) << "WRITE INTO " << filename << "ERROR"; 
            ofs.close();
            return false; 
        }
        ofs.close();
        return true;
    }

    /*判断是否是一个目录*/
    static bool IsDirectory(const std::string& path){
        struct stat st;                     //属性类
        int ret = stat(path.c_str(), &st);  //获取到path对应文件的属性
        if(ret < 0) return false;           //如果ret<0，说明该文件不存在，直接返回false
        return S_ISDIR(st.st_mode);         //反之，使用S_ISDIR，通过st.st_mode内的属性，判断是否是目录
    }

    /*判断是否是一个普通文件*/
    static bool IsRegularFile(const std::string& path){
        struct stat st;                     //属性类
        int ret = stat(path.c_str(), &st);  //获取到path对应文件的属性
        if(ret < 0) return false;           //如果ret<0，说明该文件不存在，直接返回false
        return S_ISREG(st.st_mode);         //反之，使用S_ISREG，通过st.st_mode内的属性，判断是否是普通文件
    }

    /*获取状态码对应的描述*/
    static std::string StatuDesc(int statu){
        if(Statu2Desc.find(statu) == Statu2Desc.end()) return "UnKnown Statu Code";
        else return Statu2Desc[statu];
    }

    /*根据不同的资源类型，Http中是要设置Content-Type字段的，这个叫做Mime的获取*/  
    /*如果传入的名字格式不对，或者后缀不存在，默认返回 application/octet-stream 表示二进制*/
    static std::string ExtMime(const std::string filename){
        size_t pos = filename.rfind(".");
        if(pos == std::string::npos) return "application/octet-stream";
        std::string suffix = filename.substr(pos);
        if(Suffix2Type.find(suffix) == Suffix2Type.end()) return "application/octet-stream";
        return Suffix2Type[suffix];
    }

    /*对Url进行编码*/
    //URL编码，避免URL中资源路径与查询字符串中的特殊字符与HTTP请求中特殊字符产生歧义
    //编码格式：将特殊字符的ascii值，转换为两个16进制字符，前缀%   C++ -> C%2B%2B
    //不编码的特殊字符： RFC3986文档规定 . - _ ~ 字母，数字属于绝对不编码字符
    //RFC3986文档规定，编码格式 %HH 
    //W3C标准中规定，查询字符串中的空格，需要编码为+， 解码则是+转空格
    static std::string UrlEncode(const std::string& url, bool convert_space_to_plus){
        std::string ret;
        for(auto& c : url){
            //isalnum是检查字符是否是数字或者字母字符的
            if(c == '.' || c == '-' || c == '_' || c == '~' || isalnum(c)) ret += c;
            else if(c == ' ') ret += ((convert_space_to_plus) ? '+' : ' ');
            else{
                char tmp[4];
                snprintf(tmp, 4, "%%%02X", c);
                ret += tmp;
            }
        }
        return ret;
    }

    static char Hex2Int(char c){
        if(isdigit(c)) return c - '0';
        else if(isupper(c)) return c - 'A' + 10;
        else if(islower(c)) return c - 'a' + 10;
        else return -1;
    }

    /*对Url进行解码*/
    static std::string UrlDecode(const std::string& url, bool convert_plus_to_space){
        std::string res;
        for (int i = 0; i < url.size(); i++) {
            if (url[i] == '+' && convert_plus_to_space == true) {
                res += ' ';
                continue;
            }
            if (url[i] == '%' && (i + 2) < url.size()) {
                char v1 = Hex2Int(url[i + 1]);
                char v2 = Hex2Int(url[i + 2]);
                char v = v1 * 16 + v2;
                res += v;
                i += 2;
                continue;
            }
            res += url[i];
        }
        return res;
    }

    /*Http的请求路径，第一个/表示的是相对根目录*/
    /*判断是否是一个有效路径：防止用户请求的时候恶意请求到站点根目录以上的内容*/
    static bool IsValidPath(const std::string& path){
        /*这里的思想：可以通过目录深度来进行判断，根据'/'进行路径分割 碰到'..'就层数-1*/
        std::vector<std::string> v;
        Split(path, "/", &v);
        int level = 0;
        for(auto& s : v){
            if(s == "..") {
                --level;
                if(level < 0) return false;   
                //这个位置需要注意的是：一旦某一个位置出到了相对根目录的上一层，也就是level < 0
                //就不能再继续操作了，直接返回false！ 因为出到了站点根目录外面，再去往下走的话，就不知道去到哪里了！
            }
            else ++level;
        }
        return true;
    }
};